﻿//Copyright Notice:  ©2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Diagnostics;
using System.Security.Principal;
using System.Text;
using System.Collections.Specialized;

namespace Microsoft.InformationSecurity.CISF.Security.AuthZServices
{
    /// <summary>
    /// Manages the Role to user mapping for AuthZ services.
    /// </summary>
    class AuthZCacheManager
    {
        #region Main
        /// <summary>
        /// Manages the Role to user mapping for AuthZ services.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string eventSource = "InfoSec AuthZ Cache Service";

            try
            {
                Collection<string> roleFilters = new Collection<string>();
                RoleMembersEntries roleMembersEntries = new RoleMembersEntries();

                EventLog.WriteEntry(eventSource, "Refresh of User to Role mappings started.", EventLogEntryType.Information, 1000);

                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                string authenticatedUser = AuthZGlobals.ParseName(identity.Name)[(int)AuthZGlobals.NamePart.sAMAccountName];
                NameValueCollection appSettings = ConfigurationManager.AppSettings;

                foreach (string key in appSettings.AllKeys)
                    roleFilters.Add(appSettings.Get(key));

                //Get roles and groups from database.
                //Get all users for each SG.
                //Update database with users and association to Roles.
                Collection<string> roles = roleMembersEntries.LoadRolesAndMembers(roleFilters, authenticatedUser, "RTDB");
                StringBuilder message = new StringBuilder("Refresh of User to Role mappings ended.\nRoles processed:");
                foreach (string role in roles)
                {
                    message.Append("\n");
                    message.Append(role);
                }

                EventLog.WriteEntry(eventSource, message.ToString(), EventLogEntryType.Information, 1001);
            }

            #region Catch
            catch (Exception e)
            {
                StringBuilder error = new StringBuilder("Error occured during AuthZ cache update process.\nMessage:  ");
                error.Append(e.Message);
                error.Append("\nStack Trace:  ");
                error.Append(e.StackTrace);
                EventLog.WriteEntry(eventSource, error.ToString(), EventLogEntryType.Information, 1001);
            }

            #endregion

        }

        #endregion

    }
}
